<?php

class QuestionsController extends Controller
{
	public $layout='menu';
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
				$arrViewaction=array('view','index','admin');
				$arrUpdateaction=array('create','update','delete');
				//return Yii::app()->GetAccessRule->get($arrViewaction,$arrUpdateaction);
        return array();
	}
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		if (!Yii::app()->user->isGuest)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
else
	 $this->redirect(Yii::app()->createUrl('/admin/login'));
	}
	
public function actionShow()
	{
		$this->layout="abc";
			$id=$_GET['q'];
			
			$this->render('getlevel',array('id'=>$id));
	}
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		if (!Yii::app()->user->isGuest)
	{
		
		$model=new Questions;
	   $modelOptions =null;
			$id="";
			$count=0;
       if(!empty($modelOptions))
		   {
		   		if(sizeof($modelOptions)<4)
		   		{
		   			$objsize=4-sizeof($modelOptions);
		   			for ($i=0;$i<$objsize;$i++)
		   			$modelOptions[]=new Options();
		   		}
		   }
		   else
		   {
         			for ($i=0;$i<4;$i++)
		   			$modelOptions[]=new Options();
       		}
  		   	
		
		if(isset($_POST['Questions']))
		{
			for($i=0;$i<4;$i++)
			{
				if($_POST['Options'][$i]['correct_option']==1)
				$count=1;
				$model->attributes=$_POST['Questions'];
				if($_POST['Questions']['quiz_id']!="" || (!empty($_POST['txtHint'])))
				$model->level=$_POST['txtHint'];
				$model->user_id=Yii::app()->user->id;
				$model->validate();
			}
			
			if($count==1)
			{
			$model->attributes=$_POST['Questions'];
			if($_POST['Questions']['quiz_id']!="" || (!empty($_POST['txtHint'])))
			{
			$model->level=$_POST['txtHint'];
			$model->user_id=Yii::app()->user->id;
			if($model->save())
			{
			
		        $valid=true;
		        foreach($modelOptions as $i=>$item)
		        {
		            if(isset($_POST['Options'][$i]))
		            {
		            	
		               $item->attributes=$_POST['Options'][$i];
		               $item->question_id=$model->id;
		            }
		              
		            $valid=$item->validate();
		            	
		           if($valid)
		           {
		    		
			        	if($item->correct_option)
			        	{
			        		$item->correct_option="yes";
			        	}
			        	else
			        	{
			        		$item->correct_option="no";
			        	}
			          $item->save();
			        } 
		           	
		        }
				Yii::app()->user->setFlash('success', "question saved successfully, add another question if you want!");
			
				$this->redirect(Yii::app()->createUrl('admin/questions/create/id/'.$model->quiz_id));
			}
			}
			else
			Yii::app()->user->setFlash('success', "select Quiz as well as level");
		}
		else 
			$model->addError('quiz_id', "please select one correct option");
		}
	
	
		$this->render('create',array(
			'model'=>$model,'items'=>$modelOptions,'id'=>$id
		));
	}
	else
	 $this->redirect(Yii::app()->createUrl('/admin/login'));
	}
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		if (!Yii::app()->user->isGuest)
	{
		$model=$this->loadModel($id);
		$modelOptions=Options::model()->findAllBySql('select * from options where question_id=:x ',array(':x'=>$_GET['id']));
			$id="";   
       if(!empty($modelOptions))
		   {
		   		if(sizeof($modelOptions)<4)
		   		{
		   			$objsize=4-sizeof($modelOptions);
		   			for ($i=0;$i<$objsize;$i++)
		   			$modelOptions[]=new Options();
		   		}
		   }
		   else
		   {
         for ($i=0;$i<4;$i++)
		   			$modelOptions[]=new Options();
       		}
		if(isset($_POST['Questions']))
		{
			$model->attributes=$_POST['Questions'];
			
			$model->level=$_POST['txtHint'];
			
		if($model->save())
			{
			
		        $valid=true;
		        foreach($modelOptions as $i=>$item)
		        {
		            if(isset($_POST['Options'][$i]))
		            {
		                $item->attributes=$_POST['Options'][$i];
		               $item->question_id=$model->id;
		            }
		              
		           $valid=$item->validate();
		            	
		           if($valid)
		           {
		    		if($item->correct_option)
			        	{
			        		$item->correct_option="yes";
			        	}
			        	else
			        	{
			        		$item->correct_option="no";
			        	}
			          $item->save();
			        } 
		           	
		        }
				Yii::app()->user->setFlash('success', "question and answers are saved successfully add another question if you want");
				$this->redirect(Yii::app()->createUrl('admin/questions/create/id/'.$model->quiz_id));	
			}
		}

		$this->render('update',array(
			'model'=>$model,'id'=>$id,'items'=>$modelOptions
		));
	}
	else
	 $this->redirect(Yii::app()->createUrl('/admin/login'));
	}

	
	public function actionDelete($id)
	{
		if (!Yii::app()->user->isGuest)
	{
		$id=$_GET['id'];
			$quiz=Options::model()->findAll('question_id=?',array($id));
			if($quiz)
			{
			foreach($quiz as $del)
			{
				$del->delete();
			}	
			$obj=Questions::model()->find('id=?',array($id));
			if($obj->delete())
			Yii::app()->user->setFlash('success', "your question get deleted successfully");
			$this->redirect(Yii::app()->createUrl('admin/questions/admin/id/'.$obj->quiz_id));
			}
	}
else
	 $this->redirect(Yii::app()->createUrl('/admin/login'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		if (!Yii::app()->user->isGuest)
	{	
		$dataProvider=new CActiveDataProvider('Questions');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}
	else
	 $this->redirect(Yii::app()->createUrl('/admin/login'));
	}
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		
		if (!Yii::app()->user->isGuest)
	{	
		if(!empty($_GET['id']))
		$id=$_GET['id'];
		else 
		$id=null;
		$model=new Questions('search');
	
		
		if(isset($_GET['id']) && $_GET['id']!="")
		{
		
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Questions']))
			$model->attributes=$_GET['Questions'];

		
		}
		$this->render('admin',array(
			'model'=>$model,'id'=>$id
		));
		
	}
	else
	 $this->redirect(Yii::app()->createUrl('/admin/login'));
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Questions::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='questions-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
public function actionChange()
		{ 
			
		 $data=Quiz::model()->find('quiz_id=?',array( $_POST['Quiz']['quiz_id']));
 		$this->render('_form',array('model'=>$data->no_of_level));
    
		}
public function actionRemove()
	        {
				$id=$_GET['id'];  //option id
				$model=$this->loadModel($id);
				if($model->correct_option=="yes")
				{
					Yii::app()->user->setFlash('error','You can\'t delete option because it is marked as YES');
					//$this->redirect(array('batchUpdate','id'=>$model->question_id));
				}
				else
				{
					$model->delete();
					Yii::app()->user->setFlash('success','You have successfully deleted!');
					//$this->redirect(array('batchUpdate','id'=>$model->question_id));
				}
				Yii::app()->end();
	        }
	        

}